<%@ Page Language="C#" Debug="true" %>
<%@ Import namespace="System.Net" %>
<%@ Import namespace="System.Collections.Generic" %>
<%@ Import namespace="Utils" %>
<%
string username = Request.Form["username"];
string password = Request.Form["password"];

string token = (string)Session["token"];

ServiceUtil.log("------------------------- adding user ------------------------------");
ServiceUtil.log("token="+token+";");

if(String.IsNullOrEmpty(token))
{
	token = ServiceUtil.getAccessToken();

	Session["token"] = token;
}

string retStr = "";
string userid = "";
string roleid = "";

for(int i = 0; i < 2; ++i) 
{
	try
	{
		retStr = ServiceUtil.addUser(token, username, password);

		break;
	}
	catch(Exception ex)
	{
		ServiceUtil.log("Error on adding user, "+ex.Message);
		if(ex.Message.ToLower().IndexOf("unauth") >= 0)
		{
			ServiceUtil.log("Refresh token and try again");

			//refresh the access token
			token = ServiceUtil.getAccessToken();

			Session["token"] = token;
		}
	}
}

try
{
	userid = ServiceUtil.findUserId(token, username);
	retStr += ServiceUtil.resetUserPassword(token, username, password);
	roleid += ServiceUtil.findRoleId(token, "user");
	retStr += ";[user]roleid="+roleid+";";
	retStr += ServiceUtil.setUserRoles(token, username, roleid, "user");
}
catch(Exception ex)
{
	ServiceUtil.log("Error on setting properties of user, "+ex.Message);
}

Response.ContentType = "application/json";
Response.Write("{\"id\":\""+userid+"\",\"token\":\""+token+"\",\"msg\":\""+retStr+"\"}");
%>